package com.easypay.demo.utils;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Base64Utils;

import javax.crypto.Cipher;
import java.io.*;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class RSAUtils {
    private static final Logger logger = LoggerFactory.getLogger(RSAUtils.class);


    private  static final String CHARSET = "UTF-8";

    public static final String KEY_ALGORITHM = "RSA";
    /**
     * 密钥库类型
     */
    public final static String KEY_STORE_TYPE_JKS = "JKS";
    public final static String KEY_STORE_TYPE_JCEKS = "JCEKS";
    public final static String KEY_STORE_TYPE_PKCS12 = "PKCS12";



    /**
     * 请求报文签名
     * @param privateKey  机构私钥字符串
     * @param content     签名原文
     * @return            签名密文
     * @throws Exception
     */
    public static String sign(String privateKey, String content, String algorithm) throws Exception {
        logger.info("sign with content:{}", content);
        Signature signature = Signature.getInstance(algorithm);
        signature.initSign(convertPrivateKey(privateKey));
        signature.update(content.getBytes(CHARSET));
        String sign = Base64Utils.encodeToString(signature.sign());
        logger.info("signature string: {}", sign);
        return sign;
    }

    public static String signSh256withRSA(String privateKey, String content){
        try {
            logger.info("sign string:{}", content);
            return sign(privateKey, content, "SHA256withRSA");
        }catch (Exception e){
            logger.error(e.getLocalizedMessage(), e);
        }
        return null;
    }

    public static boolean verifySh256withRSA(String publicKey, String signStr, String toVerify){
        try {
            logger.info("sign string:{}", signStr);
            return verify(publicKey, signStr, toVerify,"SHA256withRSA", false);
        }catch (Exception e){
            logger.error(e.getLocalizedMessage(), e);
        }
        return false;
    }

    /**
     * 返回报文验签
     * @param publicKey   公钥字符串
     * @param signStr     验签原文报文
     * @param toVerify     返回签名字符串
     * @return            验签结果
     * @throws Exception
     */
    public static boolean verify(String publicKey, String signStr, String toVerify, String algorithm, boolean isFromCert) throws Exception {
        Signature signature = Signature.getInstance(algorithm);
        signature.initVerify(isFromCert ? convertPublicKeyFromCert(publicKey) : convertPublicKey(publicKey));
        signature.update(signStr.getBytes(CHARSET));
        return signature.verify(Base64Utils.decodeFromString(toVerify));
    }
	
   
    /**
     * 对称密钥公钥加密
     * @param publicKey  公钥字符串
     * @return           加密密文
     * @throws Exception
     */
    public static String encryptByPublicKey(String publicKey, String plaintextKey, String algorithm)throws Exception {
        String result = null;
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, convertPublicKey(publicKey));
            byte[] encoded = cipher.doFinal(plaintextKey.getBytes(CHARSET));//content.getBytes(CHARSET)
            result = Base64Utils.encodeToString(encoded);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 对称密钥密文解密
     * @param privateKey    私钥字符串
     * @param content       对称密钥密文
     * @return              对称密钥明文
     * @throws Exception
     */
    public static String decryptByPrivateKey(String privateKey, String content)throws Exception {
        String result = null;
        try {
        	
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, convertPrivateKey(privateKey));
            byte[] encoded = cipher.doFinal(Base64Utils.decodeFromString(content));
            result = new String(encoded,CHARSET);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private static PrivateKey convertPrivateKey(String keyStr)throws Exception {
        String privateKeyPEM = keyStr;
        privateKeyPEM = privateKeyPEM.replace("-----BEGIN RSA PRIVATE KEY-----\n", "");
        privateKeyPEM = privateKeyPEM.replace("-----END RSA PRIVATE KEY-----", "");
        privateKeyPEM = privateKeyPEM.replaceAll("\\n", "");
        byte[] encoded = Base64Utils.decodeFromString(privateKeyPEM.trim());

        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePrivate(new PKCS8EncodedKeySpec(encoded));
    }

    private static PublicKey convertPublicKey(String keyStr)throws Exception {
        String privateKeyPEM = keyStr;
        privateKeyPEM = privateKeyPEM.replace("-----BEGIN PUBLIC KEY-----\n", "");
        privateKeyPEM = privateKeyPEM.replace("-----END PUBLIC KEY-----", "");
        privateKeyPEM = privateKeyPEM.replaceAll("\\n", "");
        byte[] encoded = Base64Utils.decodeFromString(privateKeyPEM);

        KeyFactory kf = KeyFactory.getInstance("RSA");
        RSAPublicKey pubKey = (RSAPublicKey) kf.generatePublic(new X509EncodedKeySpec(encoded));
        return pubKey;
    }

    private static PublicKey convertPublicKeyFromCert(String keyStr)throws Exception {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        Certificate certificate = certificateFactory.generateCertificate(new ByteArrayInputStream(Base64Utils.decodeFromString(keyStr)));
        return certificate.getPublicKey();
    }
    
    public static String getPublicKey(String publicKeyPath){
    	if(publicKeyPath==null){
    		throw new RuntimeException("请设置公钥证书路径！");
    	}
    	return getKeyFromKeyPath(publicKeyPath);
    }
    
    public static String getPrivateKey(String privateKeyPath){
    	if(privateKeyPath==null){
    		throw new RuntimeException("请设置私钥证书路径！");
    	}
    	return getKeyFromKeyPath(privateKeyPath);
    }

    /**
     * 读取密钥库文件，并返回对应的密钥库对象KeyStore
     * @param keyStoreFilePath   密钥库文件路径
     * @param keyStorePassword   密钥库的管理密码
     * @param keyStoreType       密钥库类型，仅支持Java本身支持的密钥库类型，JKS, JCEKS, PKCS12三种类型的密钥库
     * @return
     * @throws Exception
     */
    public static KeyStore getKeyStore(String keyStoreFilePath , String keyStorePassword , String keyStoreType) throws Exception {
        if(!KEY_STORE_TYPE_JKS.equals(keyStoreType)
                &&!KEY_STORE_TYPE_JCEKS.equals(keyStoreType)
                &&!KEY_STORE_TYPE_PKCS12.equals(keyStoreType)){
            throw new Exception("不支持的keystore type");
        }
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(new FileInputStream(keyStoreFilePath), keyStorePassword.toCharArray());
        return keyStore;
    }


    /**
     * 从密钥管理库中获取私钥对象
     * @param keystore  密钥库对象
     * @param alias 私钥在密钥管理库中的存储别名
     * @param password 私钥密码
     * @return PrivateKey 私钥对象实例
     * @throws Exception
     */
    public static PrivateKey getPrivateKey(KeyStore keystore , String alias , char[]password) throws Exception {
        PrivateKey privateKey =(PrivateKey)keystore.getKey(alias, password);
        return privateKey;
    }

	private static String getKeyFromKeyPath(String keyPath) {
		File file = new File(keyPath);
		if(!file.exists()){
			throw new RuntimeException("证书文件不存在:"+keyPath);
		}
		BufferedReader reader = null;
		StringBuffer keyString = new StringBuffer();
		String tempString = null;
		
		try {
			reader = new BufferedReader(new FileReader(file));
			while ((tempString = reader.readLine()) != null) {
				if(tempString.startsWith("--")){
					continue;
				}
				keyString.append(tempString);
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return keyString.toString();
		
	}
}